//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

import React, { useEffect, useState } from "react";
import { add_link, LINK_TYPE_API_COLL, LINK_TYPE_BUG, LINK_TYPE_DOC, LINK_TYPE_DRAW, LINK_TYPE_PAGES, LINK_TYPE_REQUIREMENT, LINK_TYPE_SPRIT, LINK_TYPE_TASK, LINK_TYPE_TEST_CASE, type ReviewInfo } from "@/api/project_review";
import type { ProjectInfo } from "@/api/project";
import { Button, Card, Form, Input, List, message, Modal, Select } from "antd";
import { type ENTRY_TYPE, ENTRY_TYPE_API_COLL, ENTRY_TYPE_DOC, ENTRY_TYPE_DRAW, ENTRY_TYPE_PAGES, ENTRY_TYPE_SPRIT, list as list_entry } from "@/api/project_entry";
import { list_requirement, REQ_SORT_UPDATE_TIME } from "@/api/project_requirement";
import { ISSUE_TYPE_BUG, ISSUE_TYPE_TASK, list as list_issue, SORT_KEY_UPDATE_TIME, SORT_TYPE_DSC } from "@/api/project_issue";
import { list_case_flat } from "@/api/project_testcase";
import { request } from "@/utils/request";
import { get_session } from "@/api/user";

const PAGE_SIZE = 10;

interface AddReviewLinkModalProps {
    reviewInfo: ReviewInfo;
    projectInfo: ProjectInfo;
    onOk: () => void;
    onCacel: () => void;
}

interface SimpleLinkItem {
    linkTargetId: string;
    linkTitle: string;
}

const AddReviewLinkModal = (props: AddReviewLinkModalProps) => {

    const [linkType, setLinkType] = useState(LINK_TYPE_DOC);
    const [keyword, setKeyword] = useState("");

    const [linkItemList, setLinkItemList] = useState<SimpleLinkItem[]>([]);
    const [totalCount, setTotalCount] = useState(0);
    const [curPage, setCurPage] = useState(0);


    const convertToEntryType = (): ENTRY_TYPE => {
        if (linkType == LINK_TYPE_SPRIT) {
            return ENTRY_TYPE_SPRIT;
        } else if (linkType == LINK_TYPE_DOC) {
            return ENTRY_TYPE_DOC;
        } else if (linkType == LINK_TYPE_PAGES) {
            return ENTRY_TYPE_PAGES;
        } else if (linkType == LINK_TYPE_API_COLL) {
            return ENTRY_TYPE_API_COLL;
        } else if (linkType == LINK_TYPE_DRAW) {
            return ENTRY_TYPE_DRAW;
        }
        return ENTRY_TYPE_DOC;
    };

    const loadLinkItemList = async () => {
        const sessionId = await get_session();

        if ([LINK_TYPE_SPRIT, LINK_TYPE_DOC, LINK_TYPE_PAGES, LINK_TYPE_API_COLL, LINK_TYPE_DRAW].includes(linkType)) {
            const entryType = convertToEntryType();
            const res = await request(list_entry({
                session_id: sessionId,
                project_id: props.projectInfo.project_id,
                list_param: {
                    filter_by_watch: false,
                    filter_by_tag_id: false,
                    tag_id_list: [],
                    filter_by_keyword: keyword != "",
                    keyword: keyword,
                    filter_by_entry_type: true,
                    entry_type_list: [entryType],
                },
                offset: PAGE_SIZE * curPage,
                limit: PAGE_SIZE,
            }));
            setLinkItemList(res.entry_list.map(item => ({
                linkTargetId: item.entry_id,
                linkTitle: item.entry_title,
            })));
            setTotalCount(res.total_count);
        } else if (linkType == LINK_TYPE_REQUIREMENT) {
            const res = await request(list_requirement({
                session_id: sessionId,
                project_id: props.projectInfo.project_id,
                filter_by_keyword: keyword != "",
                keyword: keyword,
                filter_by_has_link_issue: false,
                has_link_issue: false,
                filter_by_closed: false,
                closed: false,
                filter_by_tag_id_list: false,
                tag_id_list: [],
                filter_by_watch: false,
                offset: PAGE_SIZE * curPage,
                limit: PAGE_SIZE,
                sort_type: REQ_SORT_UPDATE_TIME,
            }));
            setLinkItemList(res.requirement_list.map(item => ({
                linkTargetId: item.requirement_id,
                linkTitle: item.base_info.title,
            })));
            setTotalCount(res.total_count);
        } else if ([LINK_TYPE_BUG, LINK_TYPE_TASK].includes(linkType)) {
            const res = await request(list_issue({
                session_id: sessionId,
                project_id: props.projectInfo.project_id,
                list_param: {
                    filter_by_issue_type: true,
                    issue_type: linkType == LINK_TYPE_TASK ? ISSUE_TYPE_TASK : ISSUE_TYPE_BUG,
                    filter_by_state: false,
                    state_list: [],
                    filter_by_create_user_id: false,
                    create_user_id_list: [],
                    filter_by_assgin_user_id: false,
                    assgin_user_id_list: [],
                    assgin_user_type: 0,
                    filter_by_sprit_id: false,
                    sprit_id_list: [],
                    filter_by_create_time: false,
                    from_create_time: 0,
                    to_create_time: 0,
                    filter_by_update_time: false,
                    from_update_time: 0,
                    to_update_time: 0,
                    filter_by_title_keyword: keyword != "",
                    title_keyword: keyword,
                    filter_by_tag_id_list: false,
                    tag_id_list: [],
                    filter_by_watch: false,
                    filter_by_task_priority: false,
                    task_priority_list: [],
                    filter_by_software_version: false,
                    software_version_list: [],
                    filter_by_bug_priority: false,
                    bug_priority_list: [],
                    filter_by_bug_level: false,
                    bug_level_list: [],
                },
                sort_type: SORT_TYPE_DSC,
                sort_key: SORT_KEY_UPDATE_TIME,
                offset: PAGE_SIZE * curPage,
                limit: PAGE_SIZE,
            }));
            setLinkItemList(res.info_list.map(item => ({
                linkTargetId: item.issue_id,
                linkTitle: item.basic_info.title,
            })));
            setTotalCount(res.total_count);
        } else if (linkType == LINK_TYPE_TEST_CASE) {
            const res = await request(list_case_flat({
                session_id: sessionId,
                project_id: props.projectInfo.project_id,
                list_param: {
                    filter_by_title: keyword != "",
                    title: keyword,
                    my_watch: false,
                },
                offset: PAGE_SIZE * curPage,
                limit: PAGE_SIZE,
            }));
            setLinkItemList(res.case_list.map(item => ({
                linkTargetId: item.case_id,
                linkTitle: item.title,
            })));
            setTotalCount(res.count);
        }
    };

    const addLink = async (linkItem: SimpleLinkItem) => {
        const sessionId = await get_session();

        await request(add_link({
            session_id: sessionId,
            project_id: props.projectInfo.project_id,
            review_id: props.reviewInfo.review_id,
            link_type: linkType,
            link_target_id: linkItem.linkTargetId,
        }));

        message.info("增加成功");
        props.onOk();
    };

    useEffect(() => {
        loadLinkItemList();
    }, [linkType, keyword, curPage]);

    return (
        <Modal open mask={false} footer={null} bodyStyle={{ padding: "0px 0px" }}
            onCancel={e => {
                e.stopPropagation();
                e.preventDefault();
                props.onCacel();
            }}>
            <Card title="增加链接" extra={
                <Form layout="inline" style={{ marginRight: "20px" }}>
                    <Form.Item>
                        <Select value={linkType} onChange={value => setLinkType(value)} style={{ width: "100px" }}>
                            <Select.Option value={LINK_TYPE_REQUIREMENT}>需求</Select.Option>
                            <Select.Option value={LINK_TYPE_BUG}>缺陷</Select.Option>
                            <Select.Option value={LINK_TYPE_TASK}>任务</Select.Option>
                            <Select.Option value={LINK_TYPE_TEST_CASE}>测试用例</Select.Option>
                            <Select.Option value={LINK_TYPE_SPRIT}>工作计划</Select.Option>
                            <Select.Option value={LINK_TYPE_DOC}>项目文档</Select.Option>
                            <Select.Option value={LINK_TYPE_PAGES}>静态网页</Select.Option>
                            <Select.Option value={LINK_TYPE_API_COLL}>接口集合</Select.Option>
                            <Select.Option value={LINK_TYPE_DRAW}>绘图白板</Select.Option>
                        </Select>
                    </Form.Item>
                    <Form.Item label="关键词">
                        <Input style={{ width: "100px" }} allowClear value={keyword} onChange={e => {
                            e.stopPropagation();
                            e.preventDefault();
                            setKeyword(e.target.value.trim());
                        }} />
                    </Form.Item>
                </Form>
            }>
                <List rowKey="linkTargetId" dataSource={linkItemList} style={{ maxHeight: "calc(100vh - 300px)", overflowY: "scroll", overflowX: "hidden" }}
                    pagination={{ current: curPage + 1, total: totalCount, pageSize: PAGE_SIZE, onChange: page => setCurPage(page - 1), hideOnSinglePage: true, showSizeChanger: false }}
                    renderItem={linkItem => (
                        <List.Item>
                            <Button type="link" disabled={props.reviewInfo.link_list.findIndex(item => (item.link_type == linkType && item.link_target_id == linkItem.linkTargetId)) != -1}
                                onClick={e => {
                                    e.stopPropagation();
                                    e.preventDefault();
                                    addLink(linkItem);
                                }}>{linkItem.linkTitle}</Button>
                        </List.Item>
                    )} />
            </Card>
        </Modal>
    );
};

export default AddReviewLinkModal;